

import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:du_application/http/HttpUtil.dart';
import 'package:du_application/model/IndexModel.dart';
import 'package:du_application/model/SelectModel.dart';
import 'package:du_application/provide/IndexProvider.dart';
import 'package:du_application/routes/application.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'GoodsCards.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class Select extends StatefulWidget {
  int offset=2;
  Channel channel;
  Select({Key key,this.channel}) : super(key: key);

  @override
  _SelectState createState() => _SelectState();

}

class _SelectState extends State<Select> {
   Channel channel;
       int offset;
           FloorGoodsList goodsList;
           List<FloorGoodsList> floorGoodsList;

  @override
  Widget build(BuildContext context) {
      
        setState(() {
        channel=widget.channel;
        offset=widget.offset;
 floorGoodsList=Provide.value<IndexProvide>(context).floorGoodsList;
goodsList= floorGoodsList.singleWhere((e)=>(e.id==channel.id),orElse: ()=>(floorGoodsList[0]));
       });
       RefreshController _refreshController =RefreshController(initialRefresh: true);
    
      ScrollController _scrollController=ScrollController();
     
      
   
      void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
   try{
      Timer t = Timer(Duration(seconds: 10000), () {
       _refreshController.loadFailed();
  });
  // and later, before the timer goes off...
  

   await HttpUtil.getInstance().get("/goods/getGoodsList?id=${channel.id}&offset=${offset}").then((data) {
      SelectModel model = SelectModel.fromJson(json.decode(data.toString()));
    
      if(offset>model.data.pages){
       
        _refreshController.loadNoData();
         return;
      }
      this.setState(() {
          goodsList.goodsList.addAll(model.data.goodsList.toList());
          widget.offset=offset+1;
         t.cancel();
      });
    
    });
   }catch(e){
     _refreshController.loadFailed();
   }
 
    

  }
    return SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        // WaterDropHeader、ClassicHeader、CustomHeader、LinkHeader、MaterialClassicHeader、WaterDropMaterialHeader
        header: ClassicHeader(
//          height: 45.0,
         releaseText: '松开手刷新',
         refreshingText: '刷新中',
         completeText: '刷新完成',
         failedText: '刷新失败',
         idleText: '下拉刷新',
        ),

        // ClassicFooter、CustomFooter、LinkFooter、LoadIndicator
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("下拉加载");
            }
            else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            }
            else if (mode == LoadStatus.failed) {
              body = Text("请求失败,请重试");
            }
            else {
              body = Text("没有数据啦");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child:ListView(
          shrinkWrap: true,
          controller: _scrollController,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setWidth(20)),
              decoration: BoxDecoration(
                color: Color.fromRGBO(255, 255, 255, 1),
              ),
              child: GridView.builder(
                controller: _scrollController,
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    //横轴元素个数
                    crossAxisCount: 4,
                    //纵轴间距
                    mainAxisSpacing: 1,
                    //横轴间距
                    crossAxisSpacing: 1,
                    //子组件宽高长度比例
                    childAspectRatio: 1.0),
                itemBuilder: (context, index) {
                
                  return item(context,channel.category[index]);
                },
                itemCount: channel.category.length,
              ),
            ),
            Container(
              margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setWidth(1)),
              decoration: BoxDecoration(
                color: Color.fromRGBO(255, 255, 255, 1),
              ),
              child: GridView.builder(
                controller: _scrollController,
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    //横轴元素个数
                    crossAxisCount: 2,
                    //纵轴间距
                    mainAxisSpacing: ScreenUtil.getInstance().setWidth(1),
                    //横轴间距
                    crossAxisSpacing: ScreenUtil.getInstance().setWidth(1),
                    //子组件宽高长度比例
                    childAspectRatio: 1.0),
                itemBuilder: (context, index){
              return   getGoodCard(context,goodsList.goodsList[index]);
                },
                itemCount: goodsList.goodsList.length,
              ),
            ),
          ],
        ));
  }
}


// class IndexPage extends StatelessWidget {
//   final Channel channel;
  
//   const IndexPage({Key key,this.channel}) : super(key: key);

//   @override
//   Widget build(BuildContext context) {
//       RefreshController _refreshController =RefreshController(initialRefresh: true);
//       List<FloorGoodsList> floorGoodsList=Provide.value<IndexProvide>(context).floorGoodsList;
//       ScrollController _scrollController=ScrollController();
//       FloorGoodsList goodsList= floorGoodsList.singleWhere((e)=>(e.id==channel.id),orElse: ()=>(floorGoodsList[0]));
     
//       void _onRefresh() async {
//     // monitor network fetch
//     await Future.delayed(Duration(milliseconds: 1000));
//     // if failed,use refreshFailed()
//     _refreshController.refreshCompleted();
//   }

//   void _onLoading() async {
//     // monitor network fetch
//     await Future.delayed(Duration(milliseconds: 1000));
//     // if failed,use loadFailed(),if no data return,use LoadNodata()
//     channel.category.add(channel.category[channel.category.length]);
    
//     _refreshController.loadComplete();
//   }
    
//     return SmartRefresher(
//         enablePullDown: true,
//         enablePullUp: true,
//         // WaterDropHeader、ClassicHeader、CustomHeader、LinkHeader、MaterialClassicHeader、WaterDropMaterialHeader
//         header: ClassicHeader(
// //          height: 45.0,
//          releaseText: '松开手刷新',
//          refreshingText: '刷新中',
//          completeText: '刷新完成',
//          failedText: '刷新失败',
//          idleText: '下拉刷新',
//         ),

//         // ClassicFooter、CustomFooter、LinkFooter、LoadIndicator
//         footer: CustomFooter(
//           builder: (BuildContext context, LoadStatus mode) {
//             Widget body;
//             if (mode == LoadStatus.idle) {
//               body = Text("pull up load");
//             }
//             else if (mode == LoadStatus.loading) {
//               body = CupertinoActivityIndicator();
//             }
//             else if (mode == LoadStatus.failed) {
//               body = Text("Load Failed!Click retry!");
//             }
//             else {
//               body = Text("No more Data");
//             }
//             return Container(
//               height: 55.0,
//               child: Center(child: body),
//             );
//           },
//         ),
//         controller: _refreshController,
//         onRefresh: _onRefresh,
//         onLoading: _onLoading,
//         child:ListView(
//           shrinkWrap: true,
//           controller: _scrollController,
//           children: <Widget>[
//             Container(
//               margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setWidth(20)),
//               decoration: BoxDecoration(
//                 color: Color.fromRGBO(255, 255, 255, 1),
//               ),
//               child: GridView.builder(
//                 controller: _scrollController,
//                 shrinkWrap: true,
//                 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//                     //横轴元素个数
//                     crossAxisCount: 4,
//                     //纵轴间距
//                     mainAxisSpacing: 1,
//                     //横轴间距
//                     crossAxisSpacing: 1,
//                     //子组件宽高长度比例
//                     childAspectRatio: 1.0),
//                 itemBuilder: (context, index) {
                
//                   return item(context,channel.category[index]);
//                 },
//                 itemCount: channel.category.length,
//               ),
//             ),
//             Container(
//               margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setWidth(1)),
//               decoration: BoxDecoration(
//                 color: Color.fromRGBO(255, 255, 255, 1),
//               ),
//               child: GridView.builder(
//                 controller: _scrollController,
//                 shrinkWrap: true,
//                 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//                     //横轴元素个数
//                     crossAxisCount: 2,
//                     //纵轴间距
//                     mainAxisSpacing: ScreenUtil.getInstance().setWidth(1),
//                     //横轴间距
//                     crossAxisSpacing: ScreenUtil.getInstance().setWidth(1),
//                     //子组件宽高长度比例
//                     childAspectRatio: 1.0),
//                 itemBuilder: (context, index){
//               return   getGoodCard(context,goodsList.goodsList[index]);
//                 },
//                 itemCount: goodsList.goodsList.length,
//               ),
//             ),
//           ],
//         ));
    
//   }
// }




Widget item(context,Category category){
  return Column(
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(right:  ScreenUtil.getInstance().setWidth(20), left: ScreenUtil.getInstance().setWidth(20)),
              child: GestureDetector(
                onTap: () => { Application.router.navigateTo(context, "/list?id=${category.id}&title=1")},
                child: Column(
                  children: <Widget>[
                  Container(
                    height: ScreenUtil.getInstance().setHeight(160),
                    child: AspectRatio(
                      child: CachedNetworkImage(
   
       imageUrl:category.picUrl,

                           fit:BoxFit.fitWidth,
                           placeholder: (context, url) =>
                               Image.asset('assets/loading.jpg'),
                           // print("111");
                         ),
                      aspectRatio: 1 / 1,
                    )
                  ),
                    Text(category.name),
                  ],
                ),
              ))
        ],
      );
}



















// class IndexPages extends StatefulWidget {
//   IndexPages({Key key}) : super(key: key);

//   @override
//   _IndexPagesState createState() => _IndexPagesState();
// }

// class _IndexPagesState extends State<IndexPages> {
//   ScrollController _scrollController;

//   List<Widget> list = new List();
//   List<Widget> list2 = new List();
//   @override
//   void initState() {
//     _scrollController = ScrollController();
//     super.initState();
//     for (int i = 1; i <= 8; i++) {
//       // list.add();
//     }

//   //   for (int i = 1; i <= 8; i++) {
//   //     list2.add(getGoodCard(context));
//   //   }
//   // }

//   @override
//   Widget build(BuildContext context) {
//     return RefreshIndicator(
//         onRefresh: () {
//           return;
//         },
//         child: ListView(
//           shrinkWrap: true,
//           controller: _scrollController,
//           children: <Widget>[
//             Container(
//               margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setWidth(20)),
//               decoration: BoxDecoration(
//                 color: Color.fromRGBO(255, 255, 255, 1),
//               ),
//               child: GridView.builder(
//                 controller: _scrollController,
//                 shrinkWrap: true,
//                 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//                     //横轴元素个数
//                     crossAxisCount: 4,
//                     //纵轴间距
//                     mainAxisSpacing: 1,
//                     //横轴间距
//                     crossAxisSpacing: 1,
//                     //子组件宽高长度比例
//                     childAspectRatio: 1.0),
//                 itemBuilder: (context, index) => list[index],
//                 itemCount: list.length,
//               ),
//             ),
//             Container(
//               margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setWidth(1)),
//               decoration: BoxDecoration(
//                 color: Color.fromRGBO(255, 255, 255, 1),
//               ),
//               child: GridView.builder(
//                 controller: _scrollController,
//                 shrinkWrap: true,
//                 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
//                     //横轴元素个数
//                     crossAxisCount: 2,
//                     //纵轴间距
//                     mainAxisSpacing: ScreenUtil.getInstance().setWidth(1),
//                     //横轴间距
//                     crossAxisSpacing: ScreenUtil.getInstance().setWidth(1),
//                     //子组件宽高长度比例
//                     childAspectRatio: 1.0),
//                 itemBuilder: (context, index) => list2[index],
//                 itemCount: list.length,
//               ),
//             ),
//           ],
//         ));
//   }
// }
